/**
 * 电机知识表前端管理JS
 */


try {
    // API基础路径
    let aapMotorKnAPI_BASE = '/api/feibiao/aap/motorkn';

    // 在DOM加载完成后设置API基础路径
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof API_BASE !== 'undefined') {
            aapMotorKnAPI_BASE = `${API_BASE}/feibiao/aap/motorkn`;
        }

    });

    // 跟踪当前页码和每页大小
    let currentPage = 0;
    let pageSize = 10;
    let currentSort = 'timestamp,desc';

    /**
     * 加载电机知识表列表 - 由main.js中的菜单点击事件调用，不应自动执行
     */
    function loadAapMotorKnList(page = 0, size = 10, sort = 'timestamp,desc') {
        // 保存当前页码和每页大小
        currentPage = page;
        pageSize = size;
        currentSort = sort;
        
        // 创建表格结构
        const mainContent = document.getElementById('mainContent');
        if (!mainContent) {
            console.error('找不到主内容区元素');
            return;
        }
        
        // 显示加载中
        mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
        
        // 构建API URL
        const url = `${aapMotorKnAPI_BASE}?page=${page}&size=${size}&sort=${sort}`;
        
        // 发送请求
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    console.error('服务器内部错误:', response.status);
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            renderAapMotorKnTable(data);
        })
        .catch(error => {
            console.error('加载电机知识表失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h3>加载失败</h3>
                    <p>${error.message}</p>
                    <button class="btn btn-primary" onclick="retryLoad()">重试</button>
                </div>`;
            showMessage('加载电机知识表失败: ' + error.message, 'error');
        });
    }

    /**
     * 重试加载数据
     */
    function retryLoad() {
        loadAapMotorKnList(currentPage, pageSize, currentSort);
    }

    /**
     * 安全截取文本，处理null或undefined
     */
    function safeSubstring(text, start, end) {
        if (!text) return '';
        return text.substring(start, end);
    }

    /**
     * 渲染电机知识表
     * @param {Object} data - 分页数据
     */
    function renderAapMotorKnTable(data) {
        const mainContent = document.getElementById('mainContent');
        
        let html = `
            <div class="content-header">
                <h2 class="content-title">电机知识表</h2>
                <button class="btn btn-primary" onclick="showAapMotorKnForm()">新增</button>
            </div>
            
            <div class="search-box">
                <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
                <select id="searchType" class="search-select">
                    <option value="hybrid">混合文本</option>
                    <option value="analysis">分析结果</option>
                </select>
                <button class="search-btn" onclick="searchAapMotorKn()">搜索</button>
            </div>
            
            <table id="aapMotorKnTable" class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>记录时间</th>
                        <th>混合文本</th>
                        <th>大模型分析结果</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        if (data.content && data.content.length > 0) {
            data.content.forEach(item => {
                // 检查和处理可能为null的内容
                const hybridDataPreview = item.hybridData ? 
                    (safeSubstring(item.hybridData, 0, 100) + (item.hybridData.length > 100 ? '...' : '')) : 
                    '<span class="text-muted">无内容</span>';
                    
                const llmAnalysisPreview = item.llmAnalysis ? 
                    (safeSubstring(item.llmAnalysis, 0, 100) + (item.llmAnalysis.length > 100 ? '...' : '')) : 
                    '<span class="text-muted">无内容</span>';
                    
                html += `
                    <tr>
                        <td>${item.id || ''}</td>
                        <td>${item.timestamp ? new Date(item.timestamp).toLocaleString() : ''}</td>
                        <td>${hybridDataPreview}</td>
                        <td>${llmAnalysisPreview}</td>
                        <td class="table-actions">
                            <a href="javascript:void(0)" onclick="viewAapMotorKn(${item.id})">查看</a>
                            <a href="javascript:void(0)" onclick="editAapMotorKn(${item.id})">编辑</a>
                            <a href="javascript:void(0)" class="delete" onclick="deleteAapMotorKn(${item.id})">删除</a>
                        </td>
                    </tr>
                `;
            });
        } else {
            html += '<tr><td colspan="5" style="text-align:center;">暂无数据</td></tr>';
        }
        
        html += `
                </tbody>
            </table>
        `;
        
        if (data.totalPages > 0) {
            html += `
                <ul class="pagination">
                    <li class="${currentPage <= 0 ? 'disabled' : ''}">
                        <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                    </li>
            `;
            
            for (let i = 0; i < data.totalPages; i++) {
                if (i === currentPage) {
                    html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
                } else {
                    html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
                }
            }
            
            html += `
                    <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                        <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                    </li>
                </ul>
            `;
        }
        
        mainContent.innerHTML = html;
    }

    /**
     * 跳转到指定页码
     * @param {number} page - 页码
     */
    function gotoPage(page) {
        currentPage = page;
        loadAapMotorKnList(page, pageSize, currentSort);
    }

    /**
     * 查看电机知识表详情
     */
    function viewAapMotorKn(id) {
        
        fetch(`${aapMotorKnAPI_BASE}/${id}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            showAapMotorKnDetail(data);
        })
        .catch(error => {
            console.error('获取电机知识表详情失败:', error);
            showMessage('获取电机知识表详情失败: ' + error.message, 'error');
        });
    }

    /**
     * 显示电机知识表详情
     * @param {Object} data - 详情数据
     */
    function showAapMotorKnDetail(data) {
        const mainContent = document.getElementById('mainContent');
        let html = `
            <div class="content-header">
                <h2 class="content-title">电机知识详情</h2>
                <button class="btn btn-default" onclick="loadAapMotorKnList()">返回列表</button>
            </div>
            <div class="data-detail">
                <div class="detail-group">
                    <label>ID:</label>
                    <div>${data.id || '--'}</div>
                </div>
                <div class="detail-group">
                    <label>记录时间:</label>
                    <div>${data.timestamp ? new Date(data.timestamp).toLocaleString() : '--'}</div>
                </div>
                <div class="detail-group">
                    <label>混合文本:</label>
                    <div><pre>${data.hybridData || '--'}</pre></div>
                </div>
                <div class="detail-group">
                    <label>大模型分析结果:</label>
                    <div><pre>${data.llmAnalysis || '--'}</pre></div>
                </div>
                <div class="detail-actions">
                    <button class="btn btn-primary" onclick="editAapMotorKn(${data.id})">编辑</button>
                    <button class="btn btn-danger" onclick="deleteAapMotorKn(${data.id})">删除</button>
                    <button class="btn btn-default" onclick="loadAapMotorKnList()">返回</button>
                </div>
            </div>
        `;
        mainContent.innerHTML = html;
    }

    /**
     * 编辑电机知识表
     */
    function editAapMotorKn(id) {
        console.log(`编辑电机知识记录: ${id}`);
        
        fetch(`${aapMotorKnAPI_BASE}/${id}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('获取到编辑数据:', data);
            showAapMotorKnForm(data);
        })
        .catch(error => {
            console.error('获取电机知识表详情失败:', error);
            showMessage('获取电机知识表详情失败: ' + error.message, 'error');
        });
    }

    /**
     * 显示电机知识表表单(新增/编辑)
     * @param {Object} data - 已有数据(编辑时传入)
     */
    function showAapMotorKnForm(data = null) {
        const mainContent = document.getElementById('mainContent');
        const isEdit = data !== null;
        
        let html = `
            <div class="content-header">
                <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机知识</h2>
                <button class="btn btn-default" onclick="loadAapMotorKnList()">返回列表</button>
            </div>
            <form id="aapMotorKnForm" class="data-form">
                ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
                
                <div class="form-group">
                    <label for="timestamp">记录时间 <span class="required">*</span></label>
                    <input type="text" id="timestamp" name="timestamp" class="form-control" 
                        value="${isEdit && data.timestamp ? new Date(data.timestamp).toLocaleString() : new Date().toLocaleString()}" readonly>
                </div>
                
                <div class="form-group">
                    <label for="hybridData">混合文本 <span class="required">*</span></label>
                    <textarea id="hybridData" name="hybridData" class="form-control" rows="8" required>${isEdit && data.hybridData ? data.hybridData : ''}</textarea>
                    <div id="hybridDataLength" class="text-muted text-right">${isEdit && data.hybridData ? data.hybridData.length : 0} 字符</div>
                </div>
                
                <div class="form-group">
                    <label for="llmAnalysis">大模型分析结果 <span class="required">*</span></label>
                    <textarea id="llmAnalysis" name="llmAnalysis" class="form-control" rows="8" required>${isEdit && data.llmAnalysis ? data.llmAnalysis : ''}</textarea>
                    <div id="llmAnalysisLength" class="text-muted text-right">${isEdit && data.llmAnalysis ? data.llmAnalysis.length : 0} 字符</div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-default" onclick="loadAapMotorKnList()">取消</button>
                </div>
            </form>
        `;
        
        mainContent.innerHTML = html;
        
        // 添加文本长度监听器
        const hybridDataTextarea = document.getElementById('hybridData');
        const llmAnalysisTextarea = document.getElementById('llmAnalysis');
        const hybridDataLength = document.getElementById('hybridDataLength');
        const llmAnalysisLength = document.getElementById('llmAnalysisLength');
        
        if (hybridDataTextarea && hybridDataLength) {
            hybridDataTextarea.addEventListener('input', function() {
                hybridDataLength.textContent = this.value.length + ' 字符';
            });
        }
        
        if (llmAnalysisTextarea && llmAnalysisLength) {
            llmAnalysisTextarea.addEventListener('input', function() {
                llmAnalysisLength.textContent = this.value.length + ' 字符';
            });
        }
        
        // 注册表单提交事件
        document.getElementById('aapMotorKnForm').addEventListener('submit', function(e) {
            e.preventDefault();
            saveAapMotorKn(this, isEdit);
        });
    }

    /**
     * 保存电机知识表
     * @param {HTMLFormElement} form - 表单元素
     * @param {boolean} isEdit - 是否为编辑模式
     */
    function saveAapMotorKn(form, isEdit) {
        // 表单验证
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        // 收集表单数据
        const formData = new FormData(form);
        const data = {};
        formData.forEach((value, key) => {
            data[key] = value;
        });
        
        // 设置时间戳
        data.timestamp = new Date().toISOString();
        
        console.log(`保存电机知识记录: ${isEdit ? data.id : '新记录'}`);
        
        // 构建请求
        const method = isEdit ? 'PUT' : 'POST';
        const url = isEdit ? `${aapMotorKnAPI_BASE}/${data.id}` : aapMotorKnAPI_BASE;
        
        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('保存成功:', data);
            showMessage(`电机知识${isEdit ? '更新' : '添加'}成功!`, 'success');
            loadAapMotorKnList(currentPage, pageSize, currentSort);
        })
        .catch(error => {
            console.error('保存电机知识表失败:', error);
            showMessage('保存电机知识表失败: ' + error.message, 'error');
        });
    }

    /**
     * 删除电机知识表
     */
    function deleteAapMotorKn(id) {
        if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
            return;
        }
        
        console.log(`删除电机知识记录: ${id}`);
        
        fetch(`${aapMotorKnAPI_BASE}/${id}`, {
            method: 'DELETE',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            showMessage('删除成功!', 'success');
            loadAapMotorKnList(currentPage, pageSize, currentSort);
        })
        .catch(error => {
            console.error('删除电机知识表失败:', error);
            showMessage('删除电机知识表失败: ' + error.message, 'error');
        });
    }

    /**
     * 搜索电机知识表
     */
    function searchAapMotorKn() {
        const keyword = document.getElementById('searchInput').value;
        const searchType = document.getElementById('searchType').value;
        
        if (!keyword.trim()) {
            // 如果关键字为空，重新加载所有数据
            loadAapMotorKnList(0, pageSize, currentSort);
            return;
        }
        
        console.log(`搜索电机知识表: 类型=${searchType}, 关键词=${keyword}`);
        
        // 显示加载中
        const mainContent = document.getElementById('mainContent');
        mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
        
        // 根据搜索类型选择正确的API端点
        const url = `${aapMotorKnAPI_BASE}/search/${searchType}?keyword=${encodeURIComponent(keyword)}&page=0&size=${pageSize}`;
        
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 500) {
                    return response.text().then(text => {
                        throw new Error(`服务器内部错误: ${text}`);
                    });
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('搜索结果:', data);
            renderAapMotorKnTable(data);
        })
        .catch(error => {
            console.error('搜索电机知识表失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h3>搜索失败</h3>
                    <p>${error.message}</p>
                    <button class="btn btn-primary" onclick="loadAapMotorKnList(0, ${pageSize}, '${currentSort}')">返回列表</button>
                </div>`;
            showMessage('搜索电机知识表失败: ' + error.message, 'error');
        });
    }

    /**
     * 格式化JSON显示
     * @param {string|Object} json - JSON字符串或对象
     * @returns {string} 格式化后的字符串
     */
    function formatJsonDisplay(json) {
        if (!json) return '';
        try {
            const obj = typeof json === 'string' ? JSON.parse(json) : json;
            return JSON.stringify(obj, null, 2);
        } catch (e) {
            return json;
        }
    }

    /**
     * 显示消息提示
     * @param {string} message - 消息内容
     * @param {string} type - 消息类型(success/error/info/warn)
     */
    function showMessage(msg, type) {
        console.log(`消息: [${type}] ${msg}`);
        
        // 检查是否有全局的 showMessage 函数
        if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
            window.showMessage(msg, type);
        } else {
            // 创建消息元素
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type} alert-dismissible fade show`;
            messageDiv.innerHTML = `
                ${msg}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            `;
            
            // 尝试查找容器
            let container = document.querySelector('.container');
            
            // 如果找不到标准容器，尝试查找主内容区
            if (!container) {
                container = document.getElementById('mainContent');
            }
            
            // 如果仍然找不到，则添加到body
            if (container) {
                container.insertBefore(messageDiv, container.firstChild);
            } else {
                document.body.appendChild(messageDiv);
            }
            
            // 自动消失
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 3000);
        }
    }
} catch (error) {
    console.error('电机知识表模块加载失败:', error);
    showMessage('电机知识表模块加载失败: ' + error.message, 'error');
} 